<template>
  <div class="jnpf-content-wrapper">
    <div class="jnpf-content-wrapper-center bg-white">
      <IlmsWrapperHead
        :title="projectInfo?.salesProjectName || '项目经理任命'"
        :versionList="versionList"
        @versionClick="versionClick"
      >
        <!-- 有按钮权限 && 不处于变更版本 -->
        <template v-if="canAddNeed && !isNewVersion" #toolbar>
          <a-button type="primary" @click="toAddedNeed">
            <template #icon>
              <PlusOutlined />
            </template>
            变更
          </a-button>
        </template>
      </IlmsWrapperHead>
      <div class="jnpf-content-wrapper-center-content">
        <!-- 是审批流程&&不是变更状态 -->
        <workFlowDetail :config="flowConfig" v-if="isFlow" />
        <Form
          v-else 
          :salesCode="salesCode"
          @submited="submitOrStorage"
        />
      </div>
    </div>
  </div>
</template>

<script name="ManagerAppoint" setup>
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useProjectStore } from '@/store/modules/project';
  import { isEmpty } from '@/utils/is';
  import { canEdit } from '@/utils/toolW';
  import { spStatusEnum } from '@/utils/spStatus';
  import { getLatestDetailCode } from '@/views/project/contract/common/api';
  import { historyProjectmanagerList, changeManager } from '@/views/project/preSale/managerAppoint/common/api';
  import Form from './Form.vue';
  import workFlowDetail from '@/views/workFlow/workFlowDetail/index.vue';

  const emitter = inject('emitter');
  const projectStore = useProjectStore();
  const { projectInfo } = storeToRefs(projectStore);
  const { toggleProjectSelect } = projectStore;

  const fid = ref(''); // 最新版本的fid【变更需要传递最新数据的fid】
  const orgManagerId = ref(''),
        salesCode = ref(''),
        formData = ref({}),
        historyList = ref([]);
  const isNewVersion = ref(false); // 是否是添加新版本

  // 流程显示条件【流程id存在 && 不能编辑=在审批状态 && 不是变更状态】
  const isFlow = computed(() => {
    return formData.value?.flowId && !canEdit(formData.value?.spStatus) && !isNewVersion.value;
  });

  const flowConfig = computed(() => {
    const data = unref(formData);
    return {
      taskId: data?.flowTaskId,
      flowId: data?.flowId,
      opType: 6,
    };
  });

  const versionList = computed(() => {
    return historyList.value.map(item => ({
      label: `项目经理任命：V${item.version}`,
      spStatus: item.spStatus,
      value: item.version,
      color: spStatusEnum[item.spStatus]?.color,
    }));
  });

  const versionClick = (row) => {
    // 所选版本的数据
    let info = historyList.value[row.value-1];
    getDetail(info);
  };

  const canAddNeed = computed(() => {
    if(historyList.value.length > 0){
      return historyList.value[historyList.value.length - 1].spStatus == '2';
    };
    return false;
  });

  // 添加新版本，重新获取交付清单进行分配；
  const toAddedNeed = async () => {
    isNewVersion.value = true;
  };

  const getHistoryList = async () => {
    if(!salesCode.value) return;
    const res = await historyProjectmanagerList(salesCode.value);
    historyList.value = res?.data; // historyListJSJ;
  };

  const getDetail = async (data = null) => {
    let where = {
      salesProjectCode: salesCode.value,
      type: 2,
    };
    const info = data || (await getLatestDetailCode(where))?.data;
    formData.value = info;
    // 赋值最新版本的fid；【存在数据不再赋值，防止切换版本查看赋值了旧版本的fid】
    if(!fid.value) fid.value = info.fid;
    orgManagerId.value = info?.orgManager?.id || '';
  };

  const submitOrStorage = () => {
    isNewVersion.value = false;
    getDetail();
    getHistoryList();
  };

  watch(
    () => projectInfo.value,
    async val => {
      if (!isEmpty(val)) {
        salesCode.value = val?.salesProjectCode;
        submitOrStorage();
      } else {
        await nextTick();
        emitter.emit('openProjectSelectModal', true);
      }
    },
    { immediate: true, },
  );

  const initProjectSelect = () => {
    toggleProjectSelect(true, {
      fieldNames: {
        label: 'salesProjectName',
        value: 'salesProjectCode',
      },
      searchInfo: {},
    });
  }; 

  initProjectSelect();

  onActivated(() => {
    initProjectSelect();
  });

  provide('fid', fid);
  provide('orgManagerId', orgManagerId);
  provide('isNewVersion', isNewVersion);
</script>

<style lang="less" scoped>
  .jnpf-content-wrapper-center-content {
    height: calc(100% - 60px);
    position: relative;
  }
</style>
